#!/bin/sh
PREREQ=""
prereqs()
{
    echo "${PREREQ}"
}

case "${1}" in
    prereqs)
        prereqs
        exit 0
        ;;
esac

. /scripts/functions
. /scripts/local
. /scripts/nfs

# for the user in the desktop began to roll back

for x in $(cat /proc/cmdline); do
	case $x in
	# The following lines blocked for security reason
	back_version=*)
		back_version=${x#back_version=}
		;;
	esac
done

if [[ "x${back_version}" != "x" ]];then
	exit 0
fi


atomic_upgrade_state=${rootmnt}/etc/deepin-upgrade-manager/state.records
atomic_upgrade_records=${rootmnt}/etc/deepin-upgrade-manager/result.records

if [[ "x${back_version}" != "x" ]] || [[ "x${backup_uuid}" != "x" ]] \
	|| [ ! -e ${atomic_upgrade_state} ] || [ -e ${atomic_upgrade_records} ];then
	exit 0
fi

repo_mount=n

repo_records_point_key=Repo_Mount_Point
repo_mount_point=$(echo "$(cat ${atomic_upgrade_state})" | awk -F "[{,:}]" '{for(i=1;i<=NF;i++){if($i~"'${repo_records_point_key}'"){print $(i+1)}}}' | sed 's/\"//g')

if test -n ${repo_mount_point};then
	if [ "${readonly}" = "y" ]; then
		mount -o rw,remount ${rootmnt}
		readonly=n
	fi

	if read_fstab_entry ${repo_mount_point}; then
		if [ ${repo_mount_point} != "/" ]; then
			mountfs ${repo_mount_point}
			repo_mount=y
			log_begin_msg "Mounting ${repo_mount_point} file system"
		fi
	fi
	echo "will rollback to ${rootmnt}${repo_mount_point}/osroot/snapshot/"
	config_path=${rootmnt}${repo_mount_point}/osroot/config/config.json
	deepin-upgrade-manager --config="${config_path}" --action=rollback --root="${rootmnt}"

	if [ "${readonly}" = "n" ]; then
		mount -o ro,remount ${rootmnt}
		readonly=y
	fi
	if [ "${repo_mount}" = "y" ]; then
		umount ${rootmnt}${repo_mount_point}
	fi
fi

